package nio.cp3_channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MappedHttp
{
    private static final String OUTPUT_FILE = "MappedHttp.out";
    private static final String LINE_SEP = "\r\n";
    private static final String SERVER_ID = "Server: Ronsoft Dummy Server";
    private static final String HTTP_HDR =
            "HTTP/1.0 200 OK" + LINE_SEP + SERVER_ID + LINE_SEP;
    private static final String HTTP_404_HDR =
            "HTTP/1.0 404 Not Found" + LINE_SEP + SERVER_ID + LINE_SEP;
    private static final String MSG_404 = "Could not open file: ";
    public static void main (String [] argv)
            throws Exception
    {

        String file = "blahblah.txt";
        ByteBuffer one = ByteBuffer.wrap(bytes(HTTP_HDR));
        ByteBuffer two = ByteBuffer.allocate(128);
        ByteBuffer[] buffers = {one, two, null};
        String contentType = "unknown/unknown";
        long contentLength = -1;
        try {
            FileInputStream fis = new FileInputStream(file);
            FileChannel channel = fis.getChannel();
            long size = channel.size();
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
            buffers[2] = map;
            contentLength = size;
            contentType = URLConnection.guessContentTypeFromName (file);
        } catch (IOException e) {
// file could not be opened; report problem
            ByteBuffer buf = ByteBuffer.allocate (128);
            String msg = MSG_404 + e + LINE_SEP;
            buf.put (bytes (msg));
            buf.flip( );
// Use the HTTP error response
            buffers [0] = ByteBuffer.wrap (bytes (HTTP_404_HDR));
            buffers [2] = buf;
            contentLength = msg.length( );
            contentType = "text/plain";
        }
        StringBuffer sb = new StringBuffer( );
        sb.append ("Content-Length: " + contentLength);
        sb.append (LINE_SEP);
        sb.append ("Content-Type: ").append (contentType);
        sb.append (LINE_SEP).append (LINE_SEP);
        two.put(bytes(sb.toString()));
        two.flip();
        FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);
        FileChannel channel = fos.getChannel();
        int cnt = 0;
        while (channel.write(buffers) > 0) {

            System.out.println(++cnt);
        }


        System.out.println ("output written to " + OUTPUT_FILE);
    }
    // Convert a string to its constituent bytes
// from the ASCII character set
    private static byte [] bytes (String string)
            throws Exception
    {
        return (string.getBytes ("US-ASCII"));
    } }